package com.tfswx.jcyw;

import com.tfswx.ruleengine.database.service.GzyqService;
import com.tfswx.ruleengine.database.util.NetworkUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpStatus;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@SpringBootApplication
@MapperScan({"com.tfswx.jcyw.ruleenginedesigner.dao"})
public class App {

    @Resource
    private GzyqService gzyqService;

    @Getter
    private String appName;
    private int port;

    @Value("${spring.profiles.active:dev}")
    private String active;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Value("${spring.application.name:}")
    public void setAppName(String appName) {
        if (StringUtils.isEmpty(appName)) {
            this.appName = "未命名项目";
        } else {
            this.appName = new String(appName.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        }
    }

    @EventListener({WebServerInitializedEvent.class})
    public void afterRun(WebServerInitializedEvent event) {
        String host = NetworkUtil.getHost();
        port = event.getWebServer().getPort();

        log.info("\n----------------------------------------------------------\n\t" +
                        "程序【{}】已经运行!\n\t" +
                        "环境：\t{}\n\t" +
                        "主页: \thttp://{}:{}\n\t" +
                        "审计: \thttp://{}:{}/actuator\n\t" +
                        //                        "日志: \thttp://{}:{}/log.html\n\t" +
                        "文档: \thttp://{}:{}/doc.html\n" +
                        "----------------------------------------------------------",
                appName, active, host, port, host, port, host, port
                //                , host, port
        );
        gzyqService.loadFnList();
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return factory -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
            factory.addErrorPages(error404Page);
        };
    }
}
